package com.examination_system.controller;

import com.examination_system.model.entity.User;
import com.examination_system.service.UserService;
import com.examination_system.service.impl.UserServiceImpl;
import com.examination_system.utils.LogUtil;
import com.examination_system.utils.Md5Util;
import com.examination_system.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet("/doedit")
public class DoEditUserServlet extends HttpServlet {
    private static final Logger LOGGER = LogUtil.getLogger();
    private UserService service = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idStr = (String) req.getParameter("id");
        String password = (String) req.getParameter("password");
        String name = (String) req.getParameter("name");
        String userTypeStr = (String) req.getParameter("userType");
        String userNo = (String) req.getParameter("userNo");
        User user =  new User();
        user.setName(name);
        user.setUserType(Integer.parseInt(userTypeStr));
        user.setUserNo(userNo);
        user.setPassword(Md5Util.md5(password));
        user.setIsDelete(0);
        if (StringUtils.isNotBlank(idStr)){
            user.setId(Long.parseLong(idStr));
            Integer isDelete = Integer.parseInt((String) req.getParameter("userNo"));
            user.setIsDelete(isDelete);
            service.update(user);
        } else {
            service.add(user);
        }
        req.getRequestDispatcher("/crud.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
